<script setup lang="ts">
  import { computed, ref, watch } from 'vue';

  const props = defineProps<{
    modelValue?: number;
    options: {
      label: string;
      value: number;
    }[];
  }>();

  const emit = defineEmits(['update:modelValue']);

  const localValue = ref<number[]>([]);

  const parentModelValue = computed(() => {
    return props.modelValue || 0;
  });

  watch(
    [parentModelValue],
    () => {
      const list: number[] = [];
      props.options.forEach((item) => {
        // eslint-disable-next-line no-bitwise
        if ((item.value & parentModelValue.value) === item.value) {
          list.push(item.value);
        }
      });
      localValue.value = list;
    },
    {
      immediate: true,
    }
  );

  const handleChanged = (value: number[]) => {
    localValue.value = value;
    let result = 0b0000000000;
    value.forEach((i) => {
      // eslint-disable-next-line no-bitwise
      result |= i;
    });
    emit('update:modelValue', result === 0 ? undefined : result);
  };
</script>

<template>
  <a-checkbox-group
    :model-value="localValue"
    :options="options"
    @change="handleChanged($event as number[])"
  ></a-checkbox-group>
</template>
